<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <label for="unDebounceInput">用户搜索</label>
        <input type="text" id="unDebounceInput" placeholder="请输入要搜索的用户名字">
    </div>
    <ul id="users">

    </ul>
    <script>
        const oUL = document.querySelector('#users');
        // 通往后端接口
        const oInput = document.getElementById('unDebounceInput');
        // 当作为事件的处理函数来用时，this 指向事件的目标元素
        const debounceNameSearch = debounce(handleNameSearch, 500);
        oInput.addEventListener('keyup',handleNameSearch)

        function handleNameSearch () {
            let value = this.value.trim();
            if (value === '') {
                oUL.innerHTML = '';
                return;
            }
            fetch('http://localhost:3001/users')
                .then(res => res.json())
                .then(users => {
                    // console.log(users);
                    // 箭头函数的优雅 + filter 新功能
                    const filterUsers = users.filter(user => user.name.includes(value))

                    oUL.innerHTML = filterUsers.map(function (user, idnex) {       // 和foreach不同的是，map会返回一个新数组，不会改变原数组
                        return `
                        <li>${user.name}</li>
                        `
                    }
                    );
                    // oUL.innerHTML = '';
                    // for (let user of filterUsers) {
                    //     const oLI = document.createElement('li');
                    //     oLI.innerText = user.name;
                    //     oUL.appendChild(oLI);
                    // }
                    // console.log(filterUsers);
                })
        }

        // 防抖函数
        //高阶函数
        function debounce(fu,delay){
          let vable = oInput.value.trim();
            return function(){
              clearTimeout(id);
            fn.id = setTimeout(()=>{
                fn()
              },delay)
             // console.log('////')
             //限流？
            fn()
            }
    }
    </script>
</body>

</html>